package com.google.rui.utils;

import java.io.File;
import java.util.List;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;

public class AndroidUtils {
	/**
	 * Indicates whether the specified action can be used as an intent. This
	 * method queries the package manager for installed packages that can
	 * respond to an intent with the specified action. If no suitable package is
	 * found, this method returns false.
	 *
	 * @param context The application's environment.
	 * @param action The Intent action to check for availability.
	 *
	 * @return True if an Intent with the specified action can be sent and
	 *         responded to, false otherwise.
	 */
	public static boolean isIntentAvailable(Context context, String action) {
	    final PackageManager packageManager = context.getPackageManager();
	    final Intent intent = new Intent(action);
	    List<ResolveInfo> list =
	            packageManager.queryIntentActivities(intent,
	                    PackageManager.MATCH_DEFAULT_ONLY);
	    return list.size() > 0;
	}
	
	/** 
	 * Returns version code 
	 * @return
	 */
	public static int getAppVersionCode(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	/** 
	 * Returns version name 
	 * @return
	 */
	public static String getAppVersionName(Context context) {
		try {
			return context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 调用其他程序
	 * @param context
	 * @param apkPackName  程序名称
	 * @return true,调用成功； false, 调用失败或或者改程序为安装
	 */
	public static boolean initApk(Context context,String apkPackName){
		PackageManager mager = context.getPackageManager();
		Intent intent = mager
				.getLaunchIntentForPackage("com.android.iVMS_5060");
		if (intent != null) {
			context.startActivity(intent);
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 获得SDK版本号
	 * @return
	 */
	public static int getSDKVersionNumber() {
		int sdkVersion;
		try {
		sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK);
		} catch (NumberFormatException e) {
		sdkVersion = 0;
		}
		return sdkVersion;
		}
	
	/****************************************
     *    常用功能相关
     *****************************************/
	
	/**
	 * 拨打某个电话(只打开拨打界面)
	 * 
	 * @param phone
	 */
	public static void call(final String phone, Context c) {
		c.startActivity(new Intent(Intent.ACTION_DIAL, Uri
				.parse("tel:" + phone)));
	};

	/**
	   * 发送短信
	   * @param phone
	   * @param body
	   * @param c
	   */
	  public static void sendSms(Context c,String phone,String body)
	  {
		   Intent phoneIntent=new Intent(Intent.ACTION_VIEW,Uri.parse("smsto:"+phone));
			phoneIntent.setType("vnd.android-dir/mms-sms");
			phoneIntent.putExtra("sms_body", body);
			phoneIntent.putExtra("address", phone);
			c.startActivity(phoneIntent);
	  }
	  
	
	/**
	 * 安装程序
	 * 
	 * @param apkPath
	 * @param c
	 */
	public static void install(String apkPath, Context c) {
		File fi = new File(apkPath);
		if (!fi.exists())
			return;
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.fromFile(new File(apkPath)),
				"application/vnd.android.package-archive");
		c.startActivity(i);
	}
	   
	/**
	 * 卸载程序
	 * @param packageName
	 * @param c
	 * @return
	 */
	public static boolean uninstall(String packageName,Context c){
		Uri packageURI = Uri.parse("package:"+packageName);           
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);           
		c.startActivity(uninstallIntent); 
		return true;
	}

	/**
	 * 获取手机信息
	 */
	public static String getIMEI(Context c) {
		TelephonyManager telephonyManager = (TelephonyManager) c
				.getSystemService(Context.TELEPHONY_SERVICE);
		return telephonyManager.getDeviceId();

		// phoneNum = telephonyManager.getLine1Number();
		// simNum = telephonyManager.getSimSerialNumber();
		// gsmNum = telephonyManager.getSubscriberId();
	}

	/**
	 * 获取手机号码
	 */
	public static String getPhoneNumber(Context c) {
		TelephonyManager telephonyManager = (TelephonyManager) c
				.getSystemService(Context.TELEPHONY_SERVICE);
		return telephonyManager.getLine1Number();

		// phoneNum = telephonyManager.getLine1Number();
		// simNum = telephonyManager.getSimSerialNumber();
		// gsmNum = telephonyManager.getSubscriberId();
	}
	
	 /** 
	  * 在手机上打开文件的方法
	  */
	 public static void openFile(Context c,File f) {
		if (!f.exists() || c == null)
			return;

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);

		/* 调用getMIMEType()来取得MimeType */
		String type = getMIMEType(f);
		/* 设置intent的file与MimeType */
		intent.setDataAndType(Uri.fromFile(f), type);
		c.startActivity(intent);
	}

	/**
	 * 根据文件后缀名获得对应的MIME类型。
	 * @param file
	 */
	private static String getMIMEType(File file)
	{
		String type="*/*";
		String fName=file.getName();
		//获取后缀名前的分隔符"."在fName中的位置。
		int dotIndex = fName.lastIndexOf(".");
		if(dotIndex < 0){
			return type;
		}
		/* 获取文件的后缀名 */
		String end=fName.substring(dotIndex,fName.length()).toLowerCase();
		if(end=="")return type;
		//在MIME和文件类型的匹配表中找到对应的MIME类型。
		for(int i=0;i<MIME_MapTable.length;i++){
			if(end.equals(MIME_MapTable[i][0]))
				type = MIME_MapTable[i][1];
		}
		return type;
	}

	//建立一个MIME类型与文件后缀名的匹配表
	private static final String[][] MIME_MapTable={
		//{后缀名，	MIME类型}
		{".3gp",	"video/3gpp"},
		{".apk",	"application/vnd.android.package-archive"},
		{".asf",	"video/x-ms-asf"},
		{".avi",	"video/x-msvideo"},
		{".bin",	"application/octet-stream"},
		{".bmp",  	"image/bmp"},
		{".c",		"text/plain"},
		{".class",	"application/octet-stream"},
		{".conf",	"text/plain"},
		{".cpp",	"text/plain"},
		{".doc",	"application/msword"},
		{".docx",	"application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
		{".exe",	"application/octet-stream"},
		{".gif",	"image/gif"},
		{".gtar",	"application/x-gtar"},
		{".gz",		"application/x-gzip"},
		{".h",		"text/plain"},
		{".htm",	"text/html"},
		{".html",	"text/html"},
		{".jar",	"application/java-archive"},
		{".java",	"text/plain"},
		{".jpeg",	"image/jpeg"},
		{".jpg",	"image/jpeg"},
		{".js",		"application/x-javascript"},
		{".log",	"text/plain"},
		{".m3u",	"audio/x-mpegurl"},
		{".m4a",	"audio/mp4a-latm"},
		{".m4b",	"audio/mp4a-latm"},
		{".m4p",	"audio/mp4a-latm"},
		{".m4u",	"video/vnd.mpegurl"},
		{".m4v",	"video/x-m4v"},	
		{".mov",	"video/quicktime"},
		{".mp2",	"audio/x-mpeg"},
		{".mp3",	"audio/x-mpeg"},
		{".mp4",	"video/mp4"},
		{".mpc",	"application/vnd.mpohun.certificate"},		
		{".mpe",	"video/mpeg"},	
		{".mpeg",	"video/mpeg"},	
		{".mpg",	"video/mpeg"},	
		{".mpg4",	"video/mp4"},	
		{".mpga",	"audio/mpeg"},
		{".msg",	"application/vnd.ms-outlook"},
		{".ogg",	"audio/ogg"},
		{".pdf",	"application/pdf"},
		{".png",	"image/png"},
		{".pps",	"application/vnd.ms-powerpoint"},
		{".ppt",	"application/vnd.ms-powerpoint"},
		{".pptx",	"application/vnd.openxmlformats-officedocument.presentationml.presentation"},
		{".prop",	"text/plain"},
		{".rar",	"application/x-rar-compressed"},
		{".rc",		"text/plain"},
		{".rmvb",	"audio/x-pn-realaudio"},
		{".rtf",	"application/rtf"},
		{".sh",		"text/plain"},
		{".tar",	"application/x-tar"},	
		{".tgz",	"application/x-compressed"}, 
		{".txt",	"text/plain"},
		{".wav",	"audio/x-wav"},
		{".wma",	"audio/x-ms-wma"},
		{".wmv",	"audio/x-ms-wmv"},
		{".wps",	"application/vnd.ms-works"},
		//{".xml",	"text/xml"},
		{".xml",	"text/plain"},
		{".z",		"application/x-compress"},
		{".zip",	"application/zip"},
		{".xls" , 	"application/vnd.ms-excel"},
		{".xlsx" , 	"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
		{"",		"*/*"}	
	};
	
	/********************************
	 * 快捷方式设置
	 *******************************/
	
	/** 创建快捷方式广播*/
	private static final String CREATE_SHORTCUT_ACTION = "com.android.launcher.action.INSTALL_SHORTCUT";
	/** 删除快捷方式广播*/
    private static final String DROP_SHORTCUT_ACTION = "com.android.launcher.action.UNINSTALL_SHORTCUT";

    private static final String PREFERENCE_KEY_SHORTCUT_EXISTS = "IsShortCutExists";
    private static final String PREFERENCE_KEY_FIRST_OPEN_APPS = "IsFirstOpneApps";
	/**
     * 创建桌面快捷方式
     */
    public static void setUpShortCut(Context context,String shortcutName,int shortcutIconId ,boolean duplicate,String targerClass) {

        Intent intent = new Intent(CREATE_SHORTCUT_ACTION);

        // 设置快捷方式图片
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(context,shortcutIconId));

        // 设置快捷方式名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
        // 设置是否允许重复创建快捷方式 false表示不允许
        intent.putExtra("duplicate", duplicate);
        // 设置快捷方式要打开的intent
        // 第一种方法创建快捷方式要打开的目标intent
        Intent targetIntent = new Intent();
        // 设置应用程序卸载时同时也删除桌面快捷方式
        targetIntent.setAction(Intent.ACTION_MAIN);
        targetIntent.addCategory("android.intent.category.LAUNCHER");
        
        ComponentName componentName = new ComponentName(context.getPackageName(), targerClass);
        targetIntent.setComponent(componentName);
        System.out.println(componentName.toString());

        // 第二种方法创建快捷方式要打开的目标intent
        /*
         * Intent
         * targetIntent=getPackageManager().getLaunchIntentForPackage(getPackageName
         * ());
         */
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);
        // 发送广播
        context.sendBroadcast(intent);

    }

    /**
     * 删除桌面快捷方式
     */
    public static void tearDownShortCut(Context context,String targerClass) {
        Intent intent = new Intent(DROP_SHORTCUT_ACTION);
        // 指定要删除的shortcut名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "sina");
        String appClass = context.getPackageName() + "." + targerClass;
        ComponentName component = new ComponentName(context.getPackageName(), appClass);
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,new Intent().setAction(Intent.ACTION_MAIN).setComponent(component));
        context.sendBroadcast(intent);
    }
    /**
     * 创建桌面快捷方式
     */
    public static void setUpShortCut(Context context,String shortcutName,int shortcutIconId ,boolean duplicate,Class<?> targerClass) {

        Intent intent = new Intent(CREATE_SHORTCUT_ACTION);
        // 设置快捷方式图片
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(context,shortcutIconId));
        // 设置快捷方式名称
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
        // 设置是否允许重复创建快捷方式 false表示不允许
        intent.putExtra("duplicate", duplicate);
        // 设置快捷方式要打开的intent
        // 第一种方法创建快捷方式要打开的目标intent
        Intent targetIntent = new Intent();
        // 设置应用程序卸载时同时也删除桌面快捷方式
        targetIntent.setAction(Intent.ACTION_MAIN);
        targetIntent.addCategory("android.intent.category.LAUNCHER");
        targetIntent.setClass(context,targerClass);
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);
        // 发送广播
        context.sendBroadcast(intent);
    }
    
	/*******************************
	 *  显示与分辨率相关
	 ******************************/
	
	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
	 
	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	/****************************************
	 *   网络相关
	 ****************************************/
	
	/**
	 * 是否有网络环境
	 * 
	 * @param c
	 * @return
	 */
	public static boolean hasNetEnviroment(Context c) {

		ConnectivityManager connectivityManager = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);// 获取系统的连接服务
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();// 获取网络的连接情况
		if (activeNetInfo != null) {
			return activeNetInfo.isAvailable();
		}
		return false;
	}

	/**
	 * 是否WIFI连接
	 * 
	 * @param c
	 */
	public static boolean isWIFI(Context c) {

		ConnectivityManager connectivityManager = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);// 获取系统的连接服务
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();// 获取网络的连接情况
		if (activeNetInfo == null) 
			return false;
		if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			// 判断WIFI网
			return true;
		} else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
			// 判断3G网
			return false;
		}
		return false;
	}
	
	/**
	 * 是否3G网络连接
	 * 
	 * @param c
	 */
	public static boolean isMobile(Context c) {

		ConnectivityManager connectivityManager = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);// 获取系统的连接服务
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();// 获取网络的连接情况
		if (activeNetInfo == null) 
			return false;
		if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			// 判断WIFI网
			return false;
		} else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
			// 判断3G网
			return true;
		}
		return false;
	}

	/**
	 * 判断是否已经打开gps定位，如果未打开，则根据参数设置是否打开
	 * 
	 * @param isopengpssetting
	 *            如果未打开gps，是否打开GPS设置窗口
	 */
	public static Boolean openGPSSettings(Boolean isopengpssetting,
			final Context c) {
		LocationManager alm = (LocationManager) c
				.getSystemService(Context.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			return true;
			
		} else {
			
			if (isopengpssetting) {
				new AlertDialog.Builder(c)
						.setTitle("GPS")
						.setMessage("GPS未打开，是否现在打开?")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {

										// ACTION_SECURITY_SETTINGS
										Intent myIntent = new Intent(
												Settings.ACTION_LOCATION_SOURCE_SETTINGS);
										c.startActivity(myIntent);
										return;
									}
								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										return;
									}
								}).show();
				return alm
						.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
			}
			return false;
		}
	}
	
	/***********************************
	 * 存储相关
	 ***********************************/
	
	/**
	 * 是否有SD卡  
	 * @return 有true,无 false
	 */
	public static boolean hasSDCard() {
		return android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
	}
	
	/**
	 * 获取存储卡路径
	 *  @return  存储卡路径，路径带/， 无SD卡返回空字符串
	 */
	public static String getSDCardPath()
	{
		if(hasSDCard())
			return Environment.getExternalStorageDirectory()+"/";
		else
			return "";
	}
	
}
